import React, { useState, useEffect } from 'react';
import axios from 'axios';
import DataTable from 'react-data-table-component';
import { Dialog, DialogTitle, DialogContent, Button } from '@mui/material';
import AddPopulationDialog from './AddPopulationDialog';
import "./Feeding.css"
import AddNewPopulationDialog from './AddNewPopulationDialog';
import {paginationComponentOptions, customTableStyles} from '../Constants'
import { useNavigate } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';


const PopulationsPage = () => {
    const [populationGrowth, setPopulationGrowth] = useState([]);
    const [openDialog, setOpenDialog] = useState(false);
    const [openPopDialog, setPopOpenDialog] = useState(false);
    const [populations, setPopulations] = useState([]);
    const [populationFilter, setPopulationFilter] = useState("")
    const navigate = useNavigate();

  const goBack = () => {
    navigate('/home')
  };

    useEffect(() => {
        fetchData();
        fetchPopulations()
    }, []);
    useEffect(() => {
        fetchData();
    }, [populationFilter]);

    const fetchData = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/population_growth${populationFilter!== ""? "?population="+populationFilter: ""}`, {headers});
            setPopulationGrowth(response.data.populationGrowth);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    const fetchPopulations = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/population`, {headers});
            setPopulations(response.data.populations);
        } catch (error) {
            console.error('Error fetching populations:', error);
        }
    };


    const handleOpenDialog = () => {
        setOpenDialog(true);
    };

    const handleCloseDialog = () => {
        setOpenDialog(false);
    };

    const handlePopOpenDialog = () => {
        setPopOpenDialog(true);
    };

    const handlePopCloseDialog = () => {
        setPopOpenDialog(false);
    };

    const handlePopulationChange = (event) => {
        setPopulationFilter(event.target.value)
    }

    const columns = [
        { name: 'Популяция', selector: row => row.pname, sortable: true },
        { name: 'Дата и время', selector: row => new Date(row.date_time).toLocaleString(), sortable: true},
        { name: 'Количество особей', selector: row => row.number_of_individuals },
        { name: 'Падеж, шт', selector: row => row.mortality },
        { name: 'Масса особей', selector: row => row.mass_of_individuals },
        { name: 'Средняя масса особи, г', selector: row => row.average_mass },
        { name: 'Средний размер особи, см', selector: row => row.average_size },
        { name: 'Средняя масса особи, г', selector: row => row.mass_of_individuals },
    ];

    const columns_2  = [
        { 
            name: 'Наименование', 
            selector: row => row.pname 
        },
        { 
            name: 'Дата начала', 
            selector: row => new Date(row.startdate).toLocaleDateString(),
            sortable: true
        },
        { 
            name: 'Дата окончания', 
            selector: row => row.enddate ? new Date(row.enddate).toLocaleDateString() : 'Не указана' 
        },
        { 
            name: 'Активна', 
            selector: row => row.active ? 'Да' : 'Нет',
            sortable: true
        },
        { 
            name: 'Средняя стартовая масса, г', 
            selector: row => row.avg_start_mass 
        },
        { 
            name: 'Средний стартовый размер, см', 
            selector: row => row.avg_start_size 
        },
        { 
            name: 'Стартовое количество особей, шт', 
            selector: row => row.start_count 
        },
        { 
            name: 'Стартовая масса популяции, кг', 
            selector: row => row.start_population_mass 
        },
        { 
            name: 'Бассейн', 
            selector: row => row.ename,
            sortable: true
        },
        { 
            name: 'Комментарий', 
            selector: row => row.comment ? row.comment : 'Нет комментария' ,
            width: '200px'
        }
    ];
    

    return (
        <div style={{ padding: 30 }}>
             <button onClick={goBack}>
        <FontAwesomeIcon icon={faArrowLeft} /> Главное меню
      </button>
            <div className="header" style={{marginBottom: 50}}>
                <div className="left">
                    <h1 style={{ paddingLeft: '20px', fontWeight: 'normal' }}>Популяции</h1>
                </div>
                <div className="right">
                    <button onClick={handleOpenDialog}>Добавить новые данные по популяции</button>
                </div>
                <div className="right">
                    <button onClick={handlePopOpenDialog}>Добавить новую популяцию</button>
                </div>
            </div>
            <select
                value={populationFilter}
                onChange={handlePopulationChange}
                style={{margin: 0, width: '100%', marginRight: 10, paddingBlock: 5}}
            >
                <option value="">Выберите популяцию</option>
                {populations.map(eqr => (
                    <option key={eqr.pid} value={eqr.pid}>{eqr.code+" "+eqr.pname}</option>
                ))}
            </select>
            <DataTable
                columns={columns}
                data={populationGrowth}
                pagination
                defaultSortFieldId={1}
                paginationComponentOptions={paginationComponentOptions}
                customStyles={customTableStyles}
            />
            <DataTable
                columns={columns_2}
                data={populations}
                pagination
                defaultSortFieldId={1}
                sx={{width: 400}}
                paginationComponentOptions={paginationComponentOptions}
                customStyles={customTableStyles}
                title={'Популяции'}
                
            />
            <AddPopulationDialog open={openDialog} onClose={handleCloseDialog} fetchData={fetchData} />
            <AddNewPopulationDialog open={openPopDialog} onClose={handlePopCloseDialog} fetchData={fetchData} />
        </div>
    );
};

export default PopulationsPage;
